<template>
  <div class="mod-user">
    <div class="mod-user">
      <el-form :model="query" :inline="true" @keyup.enter.native="getErrorQuestionList()">
        <el-form-item>
          <el-input placeholder="学员姓名/模式名称" clearable v-model="keyWord"></el-input>
        </el-form-item>

        <el-form-item>
          <el-select clearable filterable v-model="query.grade_type" placeholder="请选择年级">
            <el-option
              v-for="item in gradeTypeList"
              :key="item.id"
              :label="item.value"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-select
            v-if="query.grade_type"
            clearable filterable
            v-model="query.subjectId"
            placeholder="请选择科目">
            <el-option
              v-for="item in changeSubjectList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
            v-if="hasPermission(['system:mode:errorQuestionList'])"
            type="primary" icon="el-icon-search" @click="getErrorQuestionList">查询</el-button>
          <el-button
            icon="el-icon-plus"
            v-if="hasPermission(['system:mode:saveErrorQuestion'])"
            type="primary" plain
            @click="addErrorQuestion">新增</el-button>

          <el-button
            type="primary"
            icon="el-icon-upload2"
            @click="exportErrorQuestionList">导出</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="errorQuestionList"
        border
        v-loading="loading"
        style="width: 100%;">

        <el-table-column
          type="selection"
          align="center"
          width="50">
        </el-table-column>


        <el-table-column
          prop="content"
          align="center"
          min-width="200"
          label="试题内容">
          <template slot-scope="scope">
            <div v-html="scope.row.content"></div>
          </template>
        </el-table-column>

  <!--      <el-table-column
          prop="code"
          align="center"
          label="课程名称">
          <template slot-scope="scope">
            <el-tag size="small">{{scope.row.course_id | getCourseName}}</el-tag>
          </template>
        </el-table-column>-->

        <el-table-column
          prop="mode_name"
          label="模式名称"
          align="center"
          width="120">
        </el-table-column>

        <el-table-column
          prop="student_name"
          align="center"
          label="学员"
          width="100">
        </el-table-column>

        <el-table-column
          prop="question_points"
          label="试题分数"
          align="center"
          width="100">
        </el-table-column>

        <el-table-column
          label="年级"
          align="center"
          width="120">
          <template slot-scope="scope">
            <el-tag size="small" >{{scope.row.grade_type | getGradeName}}</el-tag>
          </template>
        </el-table-column>

        <el-table-column
          prop="subject_name"
          align="center"
          width="100"
          label="所属科目">
        </el-table-column>

        <el-table-column
          prop="do_question_create_date"
          align="center"
          width="180"
          :formatter="formatterCreateDate"
          label="创建时间">
        </el-table-column>

        <el-table-column
          align="center"
          min-width="150"
          label="操作">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.correct_flag"
              size="small"
              type="danger">已清错</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog title="模式试题列表" :visible.sync="dialogTableVisible">
        <el-form :inline="true" :model="questionQueryForm">
          <el-form-item>
            <el-select clearable filterable v-model="questionQueryForm.grade_type" placeholder="请选择年级">
              <el-option
                v-for="item in gradeTypeList"
                :key="item.id"
                :label="item.value"
                :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-select
              v-if="questionQueryForm.grade_type"
              clearable filterable
              v-model="questionQueryForm.subjectId"
              placeholder="请选择科目">
              <el-option
                v-for="item in changeSubjectList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" plain @click="searchErrorQuestion" icon="el-icon-search">查询</el-button>
          </el-form-item>
        </el-form>
        <el-table @selection-change="selectErrorQuestion" :data="modeQuestionInfoList">
          <el-table-column
            type="selection"
            align="center"
            width="50">
          </el-table-column>

          <el-table-column
            prop="content"
            :show-overflow-tooltip="true"
            label="试题内容"
            min-width="150">
            <template slot-scope="scope">
              <div v-html="scope.row.content"></div>
            </template>
          </el-table-column>

          <el-table-column
            prop="question_type"
            label="试题类型"
            width="100">
            <template slot-scope="scope">
              <el-tag size="small" >{{scope.row.question_type | getQuestionTypeName}}</el-tag>
            </template>
          </el-table-column>

          <el-table-column
            prop="school_type"
            width="120"
            label="阶段">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.school_type === 1" size="small">小学</el-tag>
              <el-tag v-else-if="scope.row.school_type === 2" size="small">初中</el-tag>
              <el-tag v-else-if="scope.row.school_type === 3" size="small">高中</el-tag>
            </template>
          </el-table-column>

          <el-table-column
            prop="subject_name"
            label="科目"
            width="120">
          </el-table-column>

          <el-table-column
            prop="grade_type"
            width="120"
            label="年级">
            <template slot-scope="scope">
              <el-tag size="small">{{scope.row.grade_type | getGradeName}}</el-tag>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          background
          @current-change="modeQuestionCurrentChangeHandle"
          :current-page="modeQuestionCurrentPage"
          :page-size="modeQuestionPageSize"
          :total="modeQuestionTotalCount"
          layout="total, prev, pager, next, jumper">
        </el-pagination>

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogTableVisible = false">取 消</el-button>
          <el-button @click="openToUser" type="primary">添加至错题本</el-button>
        </div>
      </el-dialog>

      <el-dialog title="选择学员" :visible.sync="userInfoTableVisible">
        <el-form :inline="true">
          <el-form-item>
            <el-input placeholder="学校名称/账号/姓名" clearable v-model="userName"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" plain @click="getUserInfoList" icon="el-icon-search">查询</el-button>
          </el-form-item>
        </el-form>
        <el-table
          @selection-change="handleUserSelectionChange"
          :data="userInfoList">
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>

          <el-table-column
            property="login_name"
            label="登录名"
            width="100">
          </el-table-column>

          <el-table-column
            property="student_name"
            label="学员姓名"
            width="100">
          </el-table-column>

          <el-table-column
            property="sex"
            label="性别"
            width="80">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.sex === 1" size="small">男</el-tag>
              <el-tag v-else size="small">女</el-tag>
            </template>
          </el-table-column>

          <el-table-column
            property="school_name"
            label="学校"
            width="150">
          </el-table-column>

          <el-table-column
            min-width="100"
            label="年级">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.grade_type" size="small">{{scope.row.grade_type | getGradeName}}</el-tag>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          background
          @current-change="changeUserPage"
          :current-page="userCurrentPage"
          :page-size="userPageSize"
          :total="userTotalCount"
          layout="total, prev, pager, next, jumper">
        </el-pagination>

        <div slot="footer" class="dialog-footer">
          <el-button @click="userInfoTableVisible = false">取 消</el-button>
          <el-button @click="saveErrorQuestion" type="primary">确定</el-button>
        </div>
      </el-dialog>
      <el-pagination
        background
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        :total="totalCount"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
    </div>
  </div>
</template>
<script>
  /* eslint-disable no-unused-vars,no-trailing-spaces */
  import { getCourseList, getSubjectList, getGradeType, getQuestionTypeApi, changeGradeTypeApi, changeSchoolTypeApi } from '@/utils/education-api'
  let thisPage = null
  export default {
    name: 'errorQuestion',
    data () {
      return {
        userInfoList: [],
        userCurrentPage: 1,
        userPageSize: 10,
        userTotalCount: 0,
        courseList: [],
        subjectList: [],
        gradeTypeList: [],
        questionTypeList: [],
        currentPage: 1,
        errorQuestionList: [],
        pageSize: 10,
        totalCount: 0,
        checkedUserIds: [],
        userName: '',
        keyWord: '',
        checkedErrorQuestionIds: [],
        userInfoTableVisible: false,
        modeQuestionInfoList: [],
        modeQuestionCurrentPage: 1,
        modeQuestionPageSize: 10,
        modeQuestionTotalCount: 0,
        dialogTableVisible: false,
        errorQuestionIds: [],
        loading: true,
        changeSubjectList: [],
        query: {
          grade_type: '',
          subjectId: ''
        },
        questionQueryForm: {
          grade_type: '',
          subjectId: ''
        }
      }
    },

    beforeCreate () {
      thisPage = this
    },

    watch: {

      'query.grade_type' (val) {
        this.getSubjectListByGradeType(val)
      },

      'questionQueryForm.grade_type' (val) {
        this.getSubjectListByGradeType(val)
      }
    },

    mounted () {
      let that = this
      getCourseList(function (data) {
        that.courseList = data
      })

      getSubjectList(function (data) {
        that.subjectList = data
      })

      getQuestionTypeApi(function (data) {
        that.questionTypeList = data
      })
      getGradeType(function (data) {
        that.gradeTypeList = data
      })
      this.getErrorQuestionList()
    },

    methods: {

      getSubjectListByGradeType (val) {
        let that = this
        that.axios.get(that.$http.httpUrl('/system/subject'), {
          params: {
            sqlId: 'system.subject.list',
            gradeType: val
          }
        }).then(function (response) {
          that.changeSubjectList = response.data.data
        }).catch(function (error) {
          console.log(error)
        })
      },

      exportErrorQuestionList () {
        let that = this
        that.$confirm('请选择导出类型?', '提示', {
          distinguishCancelAndClose: true,
          confirmButtonText: '含试题答案解析',
          cancelButtonText: '不含试题答案解析'
        }).then(() => {
          const loading = that.$loading({
            lock: true,
            text: '试题导出中, 请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          that.sendExportHttp(that, 1, loading)
        })
        .catch(action => {
          if (action === 'cancel') {
            const loading = that.$loading({
              lock: true,
              text: '试题导出中, 请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            })
            that.sendExportHttp(that, 0, loading)
          }
        })
      },

      sendExportHttp (that, type, loading) {
        that.axios.post(that.$http.httpUrl('/system/mode/exportErrorQuestion'), {
          /* sqlId: 'user.question.answer.list', */
          isRight: '0',
          keyWord: that.keyWord,
          exportType: type,
          gradeType: that.query.grade_type,
          subjectId: that.query.subjectId
        }).then(function (response) {
          if (loading != null) {
            loading.close()
          }
          if (response.data.code === 1) {
            location.href = that.$http.getFileHost() + '/' + response.data.message
          } else {
            that.$message.error(response.data.message)
          }
        }).catch(function (error) {
          console.log(error)
        })
      },

      sizeChangeHandle (val) {
        this.pageSize = val
        this.currentPage = val
        this.getErrorQuestionList()
      },

      currentChangeHandle (val) {
        this.currentPage = val
        this.getErrorQuestionList()
      },

      modeQuestionCurrentChangeHandle (val) {
        this.modeQuestionCurrentPage = val
        this.addErrorQuestion()
       // this.getErrorQuestionList()
      },

      selectErrorQuestion (val) {
        this.checkedErrorQuestionIds = val
      },

      deleteErrorQuestion (question) {
        let that = this
        that.$confirm('确定删除该错题吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function () {
          that.axios.delete(that.$http.httpUrl('/system/mode/deleteErrorQuestion'), {
            data: question
          }).then(function (response) {
            if (response.data.code === 1) {
              that.$message({
                type: 'success',
                message: response.data.message
              })
              that.getErrorQuestionList()
            } else {
              that.$message({
                type: 'error',
                message: response.data.message
              })
            }
          })
        }).catch(() => {
          that.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },

      handleUserSelectionChange (val) {
        this.checkedUserIds = val
      },

      openToUser () {
        let that = this
        if (that.checkedErrorQuestionIds.length === 0) {
          that.$message.error('请选择试题')
          return
        }
        that.errorQuestionIds = []
        that.checkedErrorQuestionIds.forEach(function (item) {
          that.errorQuestionIds.push({
            questionInfoId: item.id,
            languagePointsId: item.language_points_id,
            questionMark: item.mark,
            modeId: item.mode_id
          })
        })
        that.getUserInfoList()
      },

      saveErrorQuestion () {
        let that = this
        if (that.checkedUserIds.length === 0) {
          that.$message.error('请选择学员')
          return
        }
        let studentIds = []
        that.checkedUserIds.forEach(user => {
          studentIds.push(user.student_id)
        })
        let params = {
          questionIds: that.errorQuestionIds,
          studentIds: studentIds
        }
        that.axios.post(that.$http.httpUrl('/system/mode/saveErrorQuestion'), params).then(function (response) {
          if (response.data.code === 1) {
            that.$message.success(response.data.message)
            that.dialogTableVisible = false
            that.userInfoTableVisible = false
            that.getErrorQuestionList()
          } else {
            that.$message.error(response.data.message)
          }
        }).catch(function (error) {
          console.log(error)
        })
      },

      getUserInfoList () {
        let that = this
        that.axios.get(that.$http.httpUrl('/system/userInfo'), {
          params: {
            sqlId: 'user.info.student.list',
            keyWord: that.userName,
            offset: (that.userCurrentPage - 1) * that.userPageSize,
            limit: that.userPageSize
          }
        }).then(function (response) {
          that.userInfoList = response.data.data
          that.userTotalCount = response.data.total
          that.userInfoTableVisible = true
        }).catch(function (error) {
          console.log(error)
        })
      },

      changeUserPage (val) {
        this.userCurrentPage = val
        this.getUserInfoList()
      },

      getErrorQuestionList () {
        let that = this
        that.axios.get(that.$http.httpUrl('/system/mode/getErrorQuestionList'), {
          params: {
            sqlId: 'user.question.answer.list',
            isRight: 0,
            offset: (that.currentPage - 1) * that.pageSize,
            limit: that.pageSize,
            keyWord: that.keyWord,
            gradeType: that.query.grade_type,
            subjectId: that.query.subjectId
          }
        }).then(function (response) {
          that.errorQuestionList = response.data.data
          that.totalCount = response.data.total
          that.loading = false
        }).catch(function (error) {
          console.log(error)
        })
      },

      searchErrorQuestion () {
        this.addErrorQuestion()
      },

      // 只查询非选择题及判断题
      addErrorQuestion () {
        let that = this
        that.axios.get(that.$http.httpUrl('/api/pagination'), {
          params: {
            sqlId: 'mode.question.info.list.forErrorQuestion',
            offset: (that.modeQuestionCurrentPage - 1) * that.pageSize,
            limit: that.modeQuestionPageSize,
            gradeType: that.questionQueryForm.grade_type,
            subjectId: that.questionQueryForm.subjectId
          }
        }).then(function (response) {
          that.modeQuestionInfoList = response.data.data
          that.modeQuestionTotalCount = response.data.total
          that.dialogTableVisible = true
        }).catch(function (error) {
          console.log(error)
        })
      },

      formatterCreateDate (row, column) {
        if (!row.do_question_create_date) {
          return '--'
        }
        return this.moment(row.do_question_create_date).format('YYYY-MM-DD HH:mm')
      }
    },

    filters: {
      // getCourseName (courseId) {
      //   for (let i = 0; i < thisPage.courseList.length; i++) {
      //     if (thisPage.courseList[i].id === courseId) {
      //       return thisPage.courseList[i].name
      //     }
      //   }
      // },

      // getSubjectName (subjectId) {
      //   for (let i = 0; i < thisPage.subjectList.length; i++) {
      //     if (thisPage.subjectList[i].id === subjectId) {
      //       return thisPage.subjectList[i].name
      //     }
      //   }
      // },

      getGradeName (gradeType) {
        for (let i = 0; i < thisPage.gradeTypeList.length; i++) {
          if (thisPage.gradeTypeList[i].code === gradeType) {
            return thisPage.gradeTypeList[i].value
          }
        }
      },

      getQuestionTypeName (questionType) {
        for (let i = 0; i < thisPage.questionTypeList.length; i++) {
          if (thisPage.questionTypeList[i].code === questionType) {
            return thisPage.questionTypeList[i].value
          }
        }
      }
    }
  }
</script>
